﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO.Ports;
using System.Threading;
using System.Drawing;
using System.Configuration;
namespace SMS
{
    public partial class frmConfigConnectDevice : Form
    {
        SerialPort port;
        ClassExecute.ClassExecute dt = new ClassExecute.ClassExecute();
        string error = "";
        string str = ConfigurationSettings.AppSettings["SQLConnection"];
        //"data source=115.78.226.138;uid=sa;pwd=sontrungkhoi;initial catalog=DRM-D";
        //Start Add Dai 20120620--------------------------------------------------
        private const string OD = "OD";
        private const string PV = "PV";
        private const string GV = "GV";

        private ServiceReferenceSMS.HelperServiceSoapClient helperServiceClient = new ServiceReferenceSMS.HelperServiceSoapClient();
        //End Add Dai 20120620----------------------------------------------------
        public frmConfigConnectDevice()
        {
            InitializeComponent();
        }

        private void btConnect_Click(object sender, EventArgs e)
        {
            try
            {
                //thông số kết nối port 
                port = new SerialPort(cbComPort.Text, 115200, Parity.None, 8, StopBits.One);
                port.Handshake = Handshake.RequestToSend;
                port.NewLine = System.Environment.NewLine;
                port.ReadTimeout = 6000;
                port.WriteTimeout = 5000;

                if (port.IsOpen)
                {
                    port.Close();

                }
                port.Open();
                //mở port

                port.DataReceived += new SerialDataReceivedEventHandler(port_DataReceived);

                //viết lệnh AT Command tới port
                port.WriteLine("AT\r");
                Thread.Sleep(500);

                timer1.Enabled = true;

                btClear.Enabled = true;
                btDisconnect.Enabled = true;
                btConnect.Enabled = false;
            }
            catch (Exception ex)
            {
                richTextBox1.AppendText(ex.Message);
            }
        }

        void port_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            DisplayData("Đang chạy.............");
        }

        void LoadComport()
        {
            foreach (string portname in SerialPort.GetPortNames())
            {
                cbComPort.Items.Add(portname);
            }
        }

        private void frmConfigConnectDevice_Load(object sender, EventArgs e)
        {
            LoadComport();
            btClear.Enabled = false;
            btDisconnect.Enabled = false;
        }

        private void btDisconnect_Click(object sender, EventArgs e)
        {
            if (port.IsOpen)
            {
                port.Close();
                timer1.Enabled = false;
                btConnect.Enabled = true;

                btDisconnect.Enabled = false;
                btClear.Enabled = false;
            }
        }

        [STAThread]
        private void DisplayData(string msg)
        {
            richTextBox1.Invoke(new EventHandler(delegate
            {
                richTextBox1.SelectedText = string.Empty;
                richTextBox1.SelectionFont = new Font(richTextBox1.SelectionFont, FontStyle.Bold);

                richTextBox1.AppendText(msg);
                richTextBox1.ScrollToCaret();
            }));
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            //ReciveSMS();
            ReadSMS();
            SendSMS();
        }
        [STAThread]
        void ReadSMS()
        {
            port.WriteLine("AT+CMGL=\"REC UNREAD\"");
            String result = port.ReadExisting();
            try
            {
                String[] chuoi = result.Split(char.Parse(","));
                String[] chuoi2 = chuoi[5].Split(char.Parse("\""));


                //dt = new ClassExecute.ClassExecute();
                //dt.ExecuteSQl_bool(str, CommandType.StoredProcedure, "k_insertSMSToInbox", ref error,
                //    new SqlParameter("@Tel", chuoi[2].ToString()),
                //    new SqlParameter("@Msg", chuoi2[1].ToString().Substring(0, chuoi2[1].ToString().Length - 2)));

            
                string MsgSMS = chuoi2[1].ToString().Substring(0, chuoi2[1].ToString().Length - 2);
                MsgSMS = MsgSMS.Replace("\r\n", ""); 

                //for (int i = 0; i < MsgSMS.Length; i++)
                //{
                //    if (Convert.ToUInt32(MsgSMS[i]) == 13)
                //        MsgSMS.Replace(MsgSMS[i], ' ');
                    
                //}
                helperServiceClient.GetSmsMsg(chuoi[2].ToString(), MsgSMS);
            }
            catch
            {
            }

        }
        [STAThread]
        void SendSMS()
        {

            DataSet db = helperServiceClient.ResultSMS();
            if (db.Tables.Count > 0)
            {
                if (db.Tables[0].Rows.Count > 0)
                {
                    foreach (DataRow dr in db.Tables[0].Rows)
                    {
                        port.WriteLine("AT+CMGS=\"" + dr["Tel"].ToString() + "\"\r");
                        Thread.Sleep(800);

                        port.WriteLine(dr["Msg"].ToString() + (char)26);
                        Thread.Sleep(800);
                    }
                    //port.WriteLine("AT+CMGF=1\r");
                    //Thread.Sleep(800);
                }

            }

        }

        //Start Add Dai 20120620--------------------------------------------------
        [STAThread]
        private void SendSMS(string phoneNumber, string messageContent)
        {
            port.WriteLine("AT+CMGS=\"" + phoneNumber + "\"\r");
            Thread.Sleep(800);


            port.WriteLine(messageContent + (char)26);
            Thread.Sleep(800);
        }
        //[STAThread]
        //public void ReciveSMS()
        //{
        //    port.WriteLine("AT+CMGL=\"REC UNREAD\"");
        //    String result = port.ReadExisting();

        //    // for test
        //    //String result ="AT+CMGL=\"REC UNREAD\"+CMGL:4,\"REC UNREAD\",\"+84938468098\",,\"12/06/20,15:32:35+28\"Od sp1 3;spe 9";
            
        //    try
        //    {
        //        String[] chuoi = result.Split(char.Parse(","));
        //        String[] chuoi2 = chuoi[5].Split(char.Parse("\""));

        //        string phoneNumber = string.Empty;
        //        phoneNumber = chuoi[2].ToString();

        //        // Repace \ in string------------------------------------------- 

        //        char[] ch = phoneNumber.ToCharArray();
        //        string str = string.Empty;
                
        //        for (int j = 0; j < ch.Length; j++)
        //        {
        //            if (ch[j] != 34)
        //            {
        //                str += ch[j].ToString();
        //            }
        //        }
        //        phoneNumber = str;

        //        // Repace \ in string-------------------------------------------
                
        //        string messageContent = string.Empty;
        //        messageContent = chuoi2[1].ToString().Substring(0, chuoi2[1].ToString().Length);                
               
        //        // Check SMS 

        //        if (!string.IsNullOrEmpty(messageContent))
        //        {
        //            CheckSMS(phoneNumber, messageContent);
        //        }

        //    }
        //    catch
        //    {

        //    }
        //}

        //public void CheckSMS(string phoneNumber, string messageContent)
        //{            
            
        //    string[] mes = messageContent.Split(new char[] { ';' });
        //    bool isNotFail = true;


            try
            {
                // OD SP1 10,SP2 2
                string[] strFirst = mes[0].Split(new char[] { ' ' });
                string strFunction = strFirst[0].ToString().ToUpper().Trim();


        //        switch (strFunction)
        //        {
        //            case OD:
        //                List<ServiceReferenceSMS.OrderOnline> oderOnlineList = new List<ServiceReferenceSMS.OrderOnline>();

        //                // case: the list order product have one 
        //                if (strFirst.Length == 3)
        //                {
        //                    oderOnlineList.Add(new ServiceReferenceSMS.OrderOnline
        //                    {
        //                        Itemkey = strFirst[1].ToString().Trim(),
        //                        Quantity = strFirst[2].ToString().Trim()
        //                    });

        //                    // case: the list order product have than one 
        //                    if (mes.Length > 1)
        //                    {
        //                        for (int i = 1; i < mes.Length; i++)
        //                        {
        //                            string[] item = mes[i].Split(new char[] { ' ' });
        //                            // case information of item equal two part as: ProductID, Number
        //                            if (item.Length == 2)
        //                            {
        //                                oderOnlineList.Add(new ServiceReferenceSMS.OrderOnline
        //                                {
        //                                    Itemkey = item[0].ToString().Trim(),
        //                                    Quantity = item[1].ToString().Trim()
        //                                });
        //                            }
        //                            else
        //                            {
        //                                // struct of message content is not good for order function
        //                                isNotFail = false;
        //                            }
        //                        }
        //                    }
        //                }
        //                else
        //                {
        //                    // struct of message content is not good for order function
        //                    isNotFail = false;
        //                }
                        

        //                if (isNotFail)
        //                {
        //                    string resOD = helperServiceClient.InsertOrder(phoneNumber, oderOnlineList.ToArray());
        //                    SendSMS(phoneNumber, resOD);
        //                }
        //                else
        //                {
        //                    // struct of message content is not good for order function
        //                    SendSMS(phoneNumber, "OD NG");
        //                }
        //                break;

        //            case PV:
        //                if (mes.Length > 1)
        //                {
        //                    // struct of message content is not good for PV function
        //                    SendSMS(phoneNumber, "PV NG");
        //                }
        //                else
        //                {
        //                    string[] str = mes[0].Split(new char[] { ' ' });
        //                    if (str.Length > 1)
        //                    {
        //                        SendSMS(phoneNumber, "PV NG");
        //                    }
        //                    else 
        //                    {
        //                        string resPV = helperServiceClient.GetPV(phoneNumber);
        //                        SendSMS(phoneNumber, resPV);
        //                    }
                            
        //                }
                        
        //                break;

        //            case GV:
        //                if (mes.Length > 1)
        //                {
        //                    // struct of message content is not good for GV function
        //                    SendSMS(phoneNumber, "GV NG");
        //                }
        //                else 
        //                {
        //                    string[] strgv = mes[0].Split(new char[] { ' ' });
        //                    if (strgv.Length > 1)
        //                    {
        //                        SendSMS(phoneNumber, "GV NG");
        //                    }
        //                    else
        //                    {
        //                        string resGV = helperServiceClient.GetGV(phoneNumber);
        //                        SendSMS(phoneNumber, resGV);
        //                    }
        //                }
        //                break;

        //            default:
        //                SendSMS(phoneNumber, "NG");
        //                break;
        //        }
        //    }
        //    catch
        //    {

        //    }


        //}
        //End Add Dai 20120620----------------------------------------------------

        private void btClear_Click(object sender, EventArgs e)
        {
            if (port.IsOpen)
            {
                //XÓA ALL
                port.WriteLine("AT+CMGD=1,2");
            }
        }

        //------Test SMS nhận
        public void writeFile(string msgSMS)
        {
            System.IO.File.WriteAllText(@"D:\ProjectC#\Winform\SMS\WriteFileTest\WriteText1.txt", msgSMS);

            using (System.IO.StreamWriter file = new System.IO.StreamWriter(@"D:\ProjectC#\Winform\SMS\WriteFileTest\WriteLines3.txt", true))
            {
                file.WriteLine(msgSMS);
            }
        }
    }
}
